package LeetCode.exercise;

import java.util.*;

public class LCR113 {

    public static void main(String[] args) {
        LCR113 main = new LCR113();
        int[] res = main.findOrder(2, new int[][]{});
        System.out.println(Arrays.toString(res));
    }
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        int[] in = new int[numCourses], res = new int[numCourses];
        Map<Integer, List<Integer>> edges = new HashMap<>();
        for(int i = 0; i < prerequisites.length; i++){
            int a = prerequisites[i][0], b = prerequisites[i][1];
            // b -> a
            if(!edges.containsKey(b)){
                edges.put(b, new ArrayList<>());
            }
            edges.get(b).add(a);
            in[a]++;
        }
        // 1. 入度为 0 的点放入队列
        Queue<Integer> q = new LinkedList<>();
        for(int i = 0; i < numCourses; i++){
            if(in[i] == 0){
                q.offer(i);
            }
        }
        // 2. 当队列不为空，弹出入度为 0 的点，并删除对应的边
        int cur = 0;
        while(!q.isEmpty()){
            int tmp = q.poll();
            res[cur++] = tmp;
            for(int p : edges.getOrDefault(tmp, new ArrayList<>())){
                in[p]--;
                if(in[p] == 0){
                    q.offer(p);
                }
            }
            edges.remove(tmp);
        }
        return edges.isEmpty() ? res : new int[]{};
    }
}
